package com.ym.medical.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ym.common.enums.SmsTemplateEnum;
import com.ym.common.utils.CalcUtil;
import com.ym.common.utils.SmsUtil;
import com.ym.core.exception.BusinessException;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.RelevantCertRecordDao;
import com.ym.medical.domain.bo.PushBean;
import com.ym.medical.domain.bo.PushBeanExtraVo;
import com.ym.medical.domain.entity.CertificateImageEntity;
import com.ym.medical.domain.entity.DoctorDetailsEntity;
import com.ym.medical.domain.entity.RelevantCertRecordEntity;
import com.ym.medical.domain.entity.UserEntity;
import com.ym.medical.enums.CertificateEnum;
import com.ym.medical.enums.ProsAndConsEnum;
import com.ym.medical.enums.RelevantCertRecordAuditStatus;
import com.ym.medical.enums.UserCertStateEnum;
import com.ym.medical.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * ComputerName:LAPTOP-6GI4HOI6
 * Author:625
 * Date: 2019-07-25
 * Time: 10:01:45
 * 相关认证审核记录服务实现类
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class RelevantCertRecordSVImpl extends BaseSVImpl<RelevantCertRecordEntity, RelevantCertRecordDao> implements IRelevantCertRecordSV {


    @Autowired
    private ICertificateImageSV iCertificateImageSV;

    @Autowired
    private IDoctorDetailSV iDoctorDetailSV;

    @Autowired
    private IJpushAccountSV iJpushAccountSV;

    @Autowired
    private IUserSV iUserSV;


    @Override
    public void updateBatchByIdSelective(List<RelevantCertRecordEntity> relevantCertRecords) {
        for (RelevantCertRecordEntity relevantCertRecord : relevantCertRecords) {
            this.updateById(relevantCertRecord);
        }
    }


    /**
     * 医生审核(身份资质一起审核)
     *
     * @param certRecord
     * @return
     */
    @Override
    public int doctorReview02(RelevantCertRecordEntity certRecord) {
        String status = null;
        int rows = 0;
        if (StringUtils.isNotBlank(certRecord.getAuditStatus())) {
            status = certRecord.getAuditStatus();
        }
        Long doctId = certRecord.getUserId();
        //通过
        if (RelevantCertRecordAuditStatus.APPROVED.getKey().equals(status)) {
            if (null == certRecord.getImageNegative() && null == certRecord.getImagePositive()) {
                throw new BusinessException("请确认身份证 正反资料完整");
            }
            if (null == certRecord.getExtFile()) {
                throw new BusinessException("请确认资质 资料完整");
            }

            //查询记录 是否已经审核通过 身份

            CertificateImageEntity identityImage  = iCertificateImageSV.selectOne(
                    TK.select(CertificateImageEntity.class)
                    .where().andEqualTo(CertificateImageEntity::getDoctId,doctId)
                    .andEqualTo(CertificateImageEntity::getImgType,"01").end().limit(1)
            );
            if (identityImage != null) {
                throw new BusinessException("请勿重复审核操作");
            }
            //放入认证表  正面  CertificateEnum
            CertificateImageEntity imageEntity =
                    CertificateImageEntity.builder().doctId(doctId)
                    .fileInforId(certRecord.getImagePositive())
                    .frontBack(ProsAndConsEnum.POSITIVE.getKey())
                    .imgType(CertificateEnum.ID_CARD.getKey())
                    .uploadTime(new Date())
                    .uploadUser(doctId).build();
            iCertificateImageSV.insert(imageEntity);
            //反面
            CertificateImageEntity imageEntity2 =
                    CertificateImageEntity.builder()
                            .doctId(doctId).fileInforId(certRecord.getImageNegative())
                            .frontBack(ProsAndConsEnum.THE_REVERSE.getKey())
                            .imgType(CertificateEnum.ID_CARD.getKey()).uploadTime(new Date())
                            .uploadUser(doctId).build();
            iCertificateImageSV.insert(imageEntity2);
            String str = certRecord.getExtFile();
            JSONObject jsonObject = JSONObject.parseObject(str);
            for (Map.Entry<String, Object> entries : jsonObject.entrySet()) {
                JSONArray arrays = (JSONArray) entries.getValue();
                if (entries.getValue().toString().contains(",")) {
                    for (Object imageId : arrays) {
                        //放入认证表    医师执业证/资格证/专业技术证 /或更多 CertificateEnum
                        CertificateImageEntity model03 = CertificateImageEntity.builder()
                                .doctId(doctId).fileInforId((String) imageId)
                                .frontBack(ProsAndConsEnum.POSITIVE.getKey())
                                .imgType(entries.getKey()).uploadTime(new Date())
                                .uploadUser(doctId).build();
                        iCertificateImageSV.insert(model03);
                    }
                } else {
                    CertificateImageEntity model04 = CertificateImageEntity.builder()
                            .doctId(doctId).fileInforId((String) arrays.get(0))
                            .frontBack(ProsAndConsEnum.POSITIVE.getKey())
                            .imgType(entries.getKey()).uploadTime(new Date())
                            .uploadUser(doctId).build();
                    iCertificateImageSV.insert(model04);
                    System.out.println(entries.getKey() + " " + arrays.get(0));
                }

            }
            //改记录表
            certRecord.setAuditStatus(RelevantCertRecordAuditStatus.APPROVED.getKey());
            rows = updateState(doctId, UserCertStateEnum.CERTIFIED.getKey(), certRecord, true);
            //极光推送
            pushMessage(doctId, RelevantCertRecordAuditStatus.APPROVED.getKey(), certRecord.getRemark());

            //不通过
        } else if (RelevantCertRecordAuditStatus.AUDIT_NOT_THROUGH.getKey().equals(status)) {

            //改关联表
            certRecord.setAuditStatus(RelevantCertRecordAuditStatus.AUDIT_NOT_THROUGH.getKey());
            rows = updateState(doctId, UserCertStateEnum.CETIFICATIONFAILED.getKey(), certRecord, false);
            //极光推送
            pushMessage(doctId, RelevantCertRecordAuditStatus.AUDIT_NOT_THROUGH.getKey(), certRecord.getRemark());
        } else {
            throw new BusinessException("只能勾选通过或不通过");
        }
        return rows;
    }
    /**
     * 审核状态更改
     *
     * @param doctId
     * @param state
     * @param certRecord
     */
    private int updateState(Long doctId, String state, RelevantCertRecordEntity certRecord, boolean bool) {
        int rows = 0;
        //改医生表
        DoctorDetailsEntity model1 = DoctorDetailsEntity.builder()
                .doctId(doctId)
                .qualificationStatus(state)
                .qualificationTime(bool ? new Date() : null).build();
        iDoctorDetailSV.updateById(model1);
        //改用户表
        UserEntity entity = new UserEntity();
        entity.setId(doctId);
        entity.setCertState(state);
        iUserSV.updateById(entity);
        //改记录表
        rows = mapper.updateByPrimaryKeySelective(certRecord);
        return rows;
    }

    /**
     * 审核消息推送医生
     *
     * @param doctId
     * @param state
     */
    private void pushMessage(Long doctId, String state, String remark) {
        //极光推送
        PushBean pushBean = new PushBean();
        PushBeanExtraVo extraVo = new PushBeanExtraVo();
        extraVo.setMsgTypeParent("01");
        extraVo.setMsgTypeSub("01");
        UserEntity user = iUserSV.selectById(doctId);
        extraVo.setPushWho(user);
        extraVo.setStatus(state);
        //extraVo.setContent(user.getRealName()+" 您的认证已经通过审核");
        extraVo.setTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        pushBean.setAlert("认证通过");
        pushBean.setExtras(extraVo);
        iJpushAccountSV.pushMessage(pushBean, true);
        log.info("极光推送审核消息" + pushBean);
        //发短信
        if ("03".equals(state)) {
            //通过
            SmsUtil.sendSms(user.getPhoneNo(), SmsTemplateEnum.DATA_AUDIT_SUCCESS, CalcUtil.init(0.1).stringValue(true));
            log.info("审核通过发送短信==>" + user.getPhoneNo());
        } else if ("04".equals(state)) {
            //不通过
            SmsUtil.sendSms(user.getPhoneNo(), SmsTemplateEnum.DATA_AUDIT_FAILED, remark, "029-87590699");
            log.info("审核不通过发送短信==>" + user.getPhoneNo());
        }

    }
}
